import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper_app/api/mohu.dart';
import 'package:wallpaper_app/components/Images/image_list.dart';
import 'package:wallpaper_app/components/input/normal_input.dart';
import 'package:wallpaper_app/components/windows/window_title_bar.dart';
import 'package:wallpaper_app/model/image_base.dart';

class SearchImage extends StatefulWidget {
  const SearchImage({super.key});

  @override
  State<SearchImage> createState() => _SearchImageState();
}

class _SearchImageState extends State<SearchImage> {
  TextEditingController controller = TextEditingController();
  ScrollController scrollController = ScrollController();
  int page = 1;
  List<ImageBase> imgs = [];
  bool isLoading = false;

  void getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    Response res = await getDtImgs(keyword: controller.text, page: page);
    var data = json.decode(res.data);
    try {
      if (data['code'] == 0) {
        for (var i = 0; i < data['data'].length; i++) {
          ImageBase img = ImageBase(
            smallPath: data['data'][i]['pic']['path'],
            largePath: data['data'][i]['pic']['path'],
            tags: data['data'][i]['desc'],
            width: data['data'][i]['pic']['width'],
            height: data['data'][i]['pic']['height'],
          );
          imgs.add(img);
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent) {
        if (!isLoading) {
          page++;
          getData();
        }
      }
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        toolbarHeight: 0,
        elevation: 0,
        leading: null,
        backgroundColor: theme.primaryContainer,
        surfaceTintColor: theme.primaryContainer,
      ),
      body: Column(
        children: [
          WindowTitleBar(isBack: true),
          Expanded(
              child: Stack(
            children: [
              ImageList(
                  imageList: imgs,
                  isLoading: isLoading,
                  isWaterfallFlow: true,
                  top: 50,
                  onImageBottomLoading: () {
                    if (!isLoading) {
                      page++;
                      getData();
                    }
                  }),
              Positioned(
                top: 5,
                right: 10,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 300,
                      child: _buildSearch(),
                    ),
                  ],
                ),
              ),
            ],
          )),
        ],
      ),
    );
  }

  Widget _buildSearch() {
    return NormalInput(
      radius: 5,
      height: 40,
      icon: Icon(Icons.image_search_sharp),
      controller: controller,
      title: '关键词',
      onSubmitted: (v) {
        FocusScope.of(context).requestFocus(FocusNode());
        setState(() {
          imgs.clear();
          page = 1;
        });
        getData();
      },
    );
  }
}
